package cn.edu.hbwe.book.dao;

import java.sql.SQLException;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import cn.edu.hbwe.book.entity.User;
import cn.edu.hbwe.book.utils.DbUtil;

public class UserDao {
	/*
	 * 注册方法
	 */
	public void addUser(User user) throws SQLException {
		//1.准备sql
		String sql = "insert into user(username,password,gender,email,telephone,introduce,role,registTime) values(?,?,?,?,?,?,?,?)";
		QueryRunner runner = new QueryRunner(DbUtil.getDataSource());
		int row = runner.update(sql, user.getUsername(), user.getPassword(), user.getGender(), 
				user.getEmail(),user.getTelephone(),user.getIntroduce(),user.getRole(),user.getRegistTime()
				
				);
		if (row == 0) {
			throw new RuntimeException();
		}
	}
		//根据用户名与密码查找用户
	public User findUserByUsernameAndPassword(String username, String password) throws SQLException {
		String sql="select * from user where username=? and password=?";
		QueryRunner runner = new QueryRunner(DbUtil.getDataSource());
		return runner.query(sql, new BeanHandler<User>(User.class),username,password);
	}
	// 更新用户信息
	public void updateUserInfo(int id, String password, String gender, String telephone) throws SQLException {
		// TODO Auto-generated method stub
		String sql = "update user set password=?,gender=?,telephone=? where id=?";
		QueryRunner runner = new QueryRunner(DbUtil.getDataSource());
		int row = runner.update(sql, password, gender,telephone,id);
		if (row == 0) {
			throw new RuntimeException();
		}
	}

}
